<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\VerificationCodeRequest;

use App\Handlers\SmsUtil;
use App\Models\User;
use App\Models\SmsRecord;

class VerificationCodesController extends Controller
{
    protected $smsUtil;

    public function __construct(SmsUtil $smsUtil)
    {
        $this->smsUtil = $smsUtil;
    }

    public function store(VerificationCodeRequest $request)
    {
        $name = $request->name;

        // 生成6位随机数，左侧补0
        $code = str_pad(random_int(1, 999999), 6, 0, STR_PAD_LEFT);

        //发送短信
        $result = $this->smsUtil->sendSms($name, $code);

        if ($result->respCode ==='00000') {

            $key = 'verificationCode_'.str_random(15);
            $expiredAt = now()->addMinutes(10);
            // 缓存验证码 10分钟过期。
            \Cache::put($key, ['name' => $name, 'code' => $code], $expiredAt);

            return $this->response->array([
                'status' => true,
                'data'=>[
                    'successflag' => true,
                    'key' => $key,
                    'expired_at' => $expiredAt->toDateTimeString(),
                ],
                'message' => '发送短信成功',
            ])->setStatusCode(201);
        } else if ($result->respCode ==='00141') {
            return $this->response->array([
                'status' => false,
                'data' =>[
                    'successflag' =>false
                ],
                'message' => '一小时内发送给单个手机次数超过限制(4次).',
            ])->setStatusCode(400);
        } else {
            return $this->response->array([
                'status' => false,
                'data' =>[
                    'successflag' => false
                ],
                'message' => '发送短信失败',
            ])->setStatusCode(400);
        }
    }
}
